<template>
  <div class="background">
    <div class="head"></div>
    <div
      class="container"
      id="container"
      @mousemove="handleMousemove($event)"
      @mousedown="handleMousedown($event)"
      @mouseup="handleMouseup($event)"
    >
      <div class="code-container" id="codeContainer">
        <div
          class="left-container"
          id="leftContainer"
          :v-model="languageCurent.leftContainer"
        >
          <div class="container-topbar">
            <div class="topbar-item" @click="languageChange">
              <font-awesome-icon icon="language" style="color: #5f6477" />
            </div>
            <div class="topbar-item" @click="leftShowerController(0)">
              <span>{{ languageCurent.leftContainer.topbar[0] }}</span>
            </div>
            <div class="topbar-item" @click="leftShowerController(1)">
              <span>{{ languageCurent.leftContainer.topbar[1] }}</span>
            </div>
            <!-- <div
              class="topbar-item"
              style="border-right: none"
              @click="leftShowerController(2)"
            >
              <span>{{ languageCurent.leftContainer.topbar[2] }}</span>
            </div> -->
          </div>
          <ResourceList v-show="leftShower[0]"></ResourceList>
          <DataList
            :message="projectName"
            v-show="leftShower[1]"
            @openFile="openFile"
          ></DataList>
        </div>
        <div
          class="splitpane-handle-vertical"
          id="splitpaneVertical1"
          style="left: 30%"
        ></div>
        <div
          class="middle-container"
          id="middleContainer"
          :v-model="languageCurent.middleContainer"
        >
          <div class="container-topbar" style="left: 18px">
            <div class="topbar-item" @click="librarysShower = !librarysShower">
              <!-- 环境配置 -->
              <font-awesome-icon icon="fa-solid fa-toolbox" />
              <span style="margin-left: 5px">{{
                languageCurent.middleContainer.topbar[0]
              }}</span>
            </div>
            <div class="topbar-item" @click="runPython">
              <!-- 运行 -->
              <font-awesome-icon icon="play" />
              <span style="margin-left: 5px">{{
                languageCurent.middleContainer.topbar[1]
              }}</span>
            </div>
            <div class="topbar-item" @click="stopMoudle">
              <font-awesome-icon icon="stop" />
              <span style="margin-left: 5px">{{
                languageCurent.middleContainer.topbar[2]
              }}</span>
            </div>
            <div class="topbar-item" @click="codeReset">
              <font-awesome-icon icon="arrow-rotate-right" />
              <span style="margin-left: 5px">{{
                languageCurent.middleContainer.topbar[3]
              }}</span>
            </div>
            <div class="topbar-item" @click="saveCode">
              <font-awesome-icon icon="floppy-disk" />
              <span style="margin-left: 5px">{{
                //保存
                languageCurent.middleContainer.topbar[4]
              }}</span>
            </div>
            <div class="topbar-item" style="border-right: none">
              <el-select
                v-model="pythonVersion"
                class="m-2"
                placeholder="Interpreter"
                size="small"
                style="width: 96px"
              >
                <el-option
                  v-for="item in pythonVersions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <!-- <div class="topbar-item" @click="middleShowerController(0)">
              建模视图
            </div>
            <div class="topbar-item" @click="middleShowerController(1)">
              耦合视图
            </div> -->
          </div>
          <Codemirror
            v-model="code"
            :extensions="extensions"
            style="height: 100%"
            v-show="middleShower[0]"
          ></Codemirror>
          <Graph v-show="middleShower[1]"></Graph>
        </div>
        <div
          class="splitpane-handle-vertical"
          id="splitpaneVertical2"
          style="left: 80%"
        ></div>
        <div
          class="right-container"
          id="rightContainer"
          :v-model="languageCurent.rightContainer"
        >
          <div class="container-topbar" style="left: 18px">
            <div class="topbar-item">
              <span>{{ languageCurent.rightContainer.topbar[0] }}</span>
            </div>
            <!-- <div class="topbar-item">
              <span>{{ languageCurent.rightContainer.topbar[1] }}</span>
            </div>
            <div class="topbar-item" style="border-right: none">
              <span>{{ languageCurent.rightContainer.topbar[2] }}</span>
            </div> -->
          </div>
          <Result :message="runingResult"> </Result>
          <div class="clean">
            <el-button type="danger" size="small" @click="clean"
              ><font-awesome-icon icon="broom" />clean</el-button
            >
          </div>
        </div>
      </div>
      <div class="splitpane-handle-horizontal" id="splitpaneHorizontal1"></div>

      <div
        class="visual-container"
        id="visualContainer"
        :v-model="languageCurent.visualContainer"
      >
        <div class="container-topbar" style="top: 15px">
          <div class="topbar-item" @click="changeContainer('mapContainer')">
            <span>{{ languageCurent.visualContainer.topbar[0] }}</span>
          </div>

          <div
            class="topbar-item"
            style="border-right: none"
            @click="changeContainer('chartContainer')"
          >
            {{ languageCurent.visualContainer.topbar[1] }}
          </div>
          <!-- <el-button type="primary" v-model="languageCurent">{{
            languageCurent.visualContainer.topbar[0]
          }}</el-button> -->
        </div>
        <div
          id="mapContainer"
          class="map-container"
          v-show="topbarShower.visualContainer.map"
        >
          <div class="map-card">
            <font-awesome-icon
              icon="layer-group"
              class="icon"
              @click="showLayerType = !showLayerType"
            />
            <font-awesome-icon
              icon="square-plus"
              class="icon"
              @click="zoom('zoomIn')"
            />
            <font-awesome-icon
              icon="square-minus"
              class="icon"
              @click="zoom('zoomOut')"
            />
          </div>
          <div class="layers" v-show="showLayerType">
            <div class="layer-box" @click="changeLayer('tdtMap')">
              <img src="../assets/img/tdtMap.png" alt="" />
              <p>Vector</p>
            </div>
            <div class="layer-box" @click="changeLayer('tdtImg')">
              <img src="../assets/img/tdtImg.png" alt="" />
              <p>Image</p>
            </div>
          </div>
        </div>

        <div
          id="chartContainer"
          class="chart-container"
          v-show="topbarShower.visualContainer.chart"
        >
          <transition-group name="fade" mode="out-in">
            <div
              v-for="(item, index) in dataPreviewList"
              :key="item"
              class="card"
            >
              <font-awesome-icon
                :icon="['fass', 'xmark']"
                class="close_icon"
                @click="closePreview(index)"
              />

              <div class="chart-prew">
                <el-image
                  style="width: 100%; height: 100%"
                  :src="item.url"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="item.srclist"
                  fit="cover"
                  v-if="item.isImg"
                />
                <div v-if="!item.isImg" style="width: 100%; height: 100%">
                  <pre
                    v-if="item.fileContent != ''"
                    @click="openPreview(item)"
                    class="preview_text"
                    style="font-size: 8px; overflow: hidden"
                    >{{ item.fileContent }}</pre
                  >
                  <div
                    v-else
                    style="
                      width: 100%;
                      height: 100%;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                    "
                  >
                    <span style="color: #9b9b9c">Empty</span>
                  </div>
                </div>
              </div>
              <div class="title-container">
                <span>{{ item.name }}</span>
              </div>
            </div>
          </transition-group>
        </div>
      </div>
      <!-- 包信息 -->
      <div class="library-container" v-show="librarysShower">
        <el-table
          :data="packageInfor"
          style="width: 100%; border-radius: 6px"
          max-height="260"
        >
          <el-table-column prop="name" label="Package" width="180" />
          <el-table-column prop="version" label="Version" width="120" />

          <el-table-column fixed="right" label="Operations" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="editPackageInfo('remove', scope.$index)"
              >
                Remove
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="addPackage" v-show="addPackageTag">
          <div class="package-info">
            <font-awesome-icon
              style="margin-left: 5px; font-size: 10px; color: red"
              icon="star-of-life"
            />
            <label>name: </label>
            <el-input
              v-model="addedPackageInfo.name"
              placeholder="package name"
              style="width: 120px; font-size: 14px"
            />
          </div>
          <div class="package-info" style="margin-left: 4px">
            <label>version: </label>
            <el-input
              v-model="addedPackageInfo.version"
              placeholder="package version"
              style="width: 120px; font-size: 14px"
            />
          </div>
          <div class="package-info">
            <label
              style="color: #409eff; cursor: pointer"
              @click="editPackageInfo('add')"
              >confirm</label
            >
          </div>
        </div>
        <el-button
          class="mt-4"
          style="width: 100%"
          @click="addPackageTag = !addPackageTag"
          >Add Item</el-button
        >
      </div>
      <el-dialog v-model="dialogVisible" title="文件预览" width="450" draggable>
        <pre
          style="
            font-size: 12px;
            width: 430px;
            height: 400px;
            overflow: auto;
            box-sizing: border-box;
            margin: 0px 10px;
            color: black;
            box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
          "
          >{{ previewItem.fileContent }}</pre
        >
        <div
          style="
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-evenly;
            margin-top: 10px;
          "
        >
          <span
            style="
              font-size: 15px;
              font-weight: bold;
              margin-left: 150px;
              color: black;
            "
            >{{ previewItem.name }}</span
          >
          <div class="dialog-footer" style="margin-left: 50px">
            <el-button @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import { XYZ, TileWMS as TileWMSSource } from "ol/source";

import OSM from "ol/source/OSM.js";
import { defaults as defaultControls } from "ol/control.js";

import { Codemirror } from "vue-codemirror";
import { python } from "@codemirror/lang-python";
// import { oneDark } from "@codemirror/theme-one-dark";
/**组件 */
import ResourceList from "../components/ModelingComponents/ResourceList.vue";
import DataList from "../components/ModelingComponents/DataList.vue";
import Result from "../components/ModelingComponents/Result.vue";
import Graph from "../components/ModelingComponents/Graph.vue";
// eslint-disable-next-line no-unused-vars
import axios from "axios";
import { config } from "../components/ModelingComponents/Config.js";
import { ElNotification } from "element-plus";
import { uuid } from "vue-uuid";
import { fa } from "element-plus/es/locale";
// import * as echarts from "echarts";
// import WebSocket from "vue-native-websocket";
export default {
  data() {
    return {
      sceneID: "",
      /**1.分隔条拖拽相关变量 */
      containerWidth: 0,
      containerHeigth: 0,
      // 第一个分割线左边距
      splitpaneVertical1Left: "",
      splitpaneVertical2Left: "",
      // 鼠标行为标记
      mouseActTag: {
        mousedown: false,
        mouseup: false,
      },
      // 拖拽的分隔条
      activeSplitpane: null,
      topbarShower: {
        visualContainer: { map: true, chart: false },
      },
      leftShower: [true, false, false],
      middleShower: [true, false],
      /**语言切换 */
      languageTag: true,
      languageCurent: {
        visualContainer: { topbar: [] },
        leftContainer: { topbar: [] },
        middleContainer: { topbar: [] },
        rightContainer: { topbar: [] },
      },
      language: {
        English: {
          visualContainer: {
            topbar: ["Map", "Chart"],
          },
          leftContainer: {
            topbar: ["Modules", "Data", "Methods"],
          },
          middleContainer: {
            topbar: ["Environment", "Run", "Stop", "Reset", "Save"],
          },
          rightContainer: {
            topbar: ["Result", "Resource recommend", "Logic structure"],
          },
        },
        Chinese: {
          visualContainer: {
            topbar: ["地图", "图表"],
          },
          leftContainer: {
            topbar: ["模块列表", "数据列表", "方法列表"],
          },
          middleContainer: {
            topbar: ["环境", "运行", "停止", "重置", "保存"],
          },
          rightContainer: {
            topbar: ["执行结果", "资源推荐", "逻辑模型"],
          },
        },
      },
      /**地图相关变量 */
      map: new Map(),
      showLayerType: false, //切换地图类型
      layers: [],
      /**在线代码编辑相关变量 */
      projectName: "FDS",
      // code: "def print_hi(name):\n  print(f'Hello, {name}')\n\nif __name__ == '__main__':\n  print_hi('Hello world!')", // 设置默认 Python 代码
      code: "",
      extensions: [python()],
      pythonVersion: "",
      pythonVersions: [
        {
          value: "2.7",
          label: "Python 2.7",
        },
        {
          value: "3.7",
          label: "Python 3.7",
        },
        {
          value: "3.9",
          label: "Python 3.9",
        },
      ],
      runingResult: "Response...\n",
      socket: null,
      projectID: "",
      containerID: "",
      addPackageTag: false,
      packageInfor: [
        {
          name: "certifi",
          version: "2023.7.22",
        },
      ],
      addedPackageInfo: {
        name: "",
        version: "",
      },
      librarysShower: false, //依赖信息弹窗显示控制
      dataTree: [], // 目录树
      dataPreviewList: [],
      dialogVisible: false,
      previewItem: {},
    };
  },
  methods: {
    resize() {},
    // 鼠标按下事件
    handleMousedown(e) {
      this.refreshContainerSize();
      this.mouseActTag.mousedown = true;
      this.activeSplitpane = e.target;
    },
    // 鼠标移动事件
    handleMousemove(e) {
      // 控制分隔条
      if (this.mouseActTag.mousedown) {
        var percentageValue = (e.x * 100) / this.containerWidth;
        let leftContainer = document.getElementById("leftContainer");
        let middleContainer = document.getElementById("middleContainer");
        let rightContainer = document.getElementById("rightContainer");
        if (this.activeSplitpane.id == "splitpaneVertical1") {
          // 左边的分隔条，记录左边距，第一个分割条的左边距不能大于第二个分隔条
          let splitpaneVertical2 =
            document.getElementById("splitpaneVertical2");
          let splitpane2Value = Number(
            splitpaneVertical2.style.left.split("%")[0]
          ); //此时第2个分隔条的左边距

          if (
            percentageValue >
            splitpane2Value + (-8 * 100) / this.containerWidth
          ) {
            percentageValue =
              splitpane2Value + (-8 * 100) / this.containerWidth;
          }
          // 记录此刻第一个分隔条左边距的大小
          this.activeSplitpane.style.left = percentageValue + "%";
          this.splitpaneVertical1Left = this.activeSplitpane.style.left;

          // 左边和中间的容器大小改变
          leftContainer.style.width = percentageValue + "%";
          middleContainer.style.width = splitpane2Value - percentageValue + "%";
        } else if (this.activeSplitpane.id == "splitpaneVertical2") {
          // 如果右边分隔条左边距>=左边分隔条左边距
          let splitpaneVertical1 =
            document.getElementById("splitpaneVertical1");
          let splitpane1Value = Number(
            splitpaneVertical1.style.left.split("%")[0]
          ); //此时第1个分隔条的左边距
          if (
            percentageValue <
            splitpane1Value + (8 * 100) / this.containerWidth
          ) {
            percentageValue = splitpane1Value + (8 * 100) / this.containerWidth;
          }
          // 记录此刻第二个分割条的左边距
          this.activeSplitpane.style.left = percentageValue + "%";
          this.splitpaneVertical2Left = this.activeSplitpane.style.left;

          // 右边和中间的容器大小改变
          middleContainer.style.width =
            percentageValue -
            Number(this.splitpaneVertical1Left.split("%")[0]) +
            "%";

          rightContainer.style.width = 100 - percentageValue + "%";
        } else if (this.activeSplitpane.id == "splitpaneHorizontal1") {
          //动态改变分隔条位置
          percentageValue = ((e.y - 71) * 100) / this.containerHeigth;
          this.activeSplitpane.style.top = percentageValue + "%";
          // 动态更改上下容器的大小
          let codeContainer = document.getElementById("codeContainer");
          let visualContainer = document.getElementById("visualContainer");
          codeContainer.style.height = percentageValue + "%";
          visualContainer.style.height = 100 - percentageValue + "%";
        }
      }
    },
    // 鼠标松开事件
    handleMouseup() {
      this.mouseActTag.mouseup = true;
      this.mouseActTag.mousedown = false;
    },
    // 更新container的宽和高
    refreshContainerSize() {
      var divElement = document.getElementById("container");
      this.containerWidth = divElement.offsetWidth;
      this.containerHeigth = divElement.offsetHeight;
    },
    // container切换
    changeContainer(type) {
      switch (type) {
        case "mapContainer":
          this.topbarShower.visualContainer.map = true;
          this.topbarShower.visualContainer.chart = false;
          break;
        case "chartContainer":
          this.topbarShower.visualContainer.map = false;
          this.topbarShower.visualContainer.chart = true;
          break;
        default:
          break;
      }
    },
    // 语言切换
    languageChange() {
      this.languageTag = !this.languageTag;
      if (this.languageTag) {
        this.languageCurent = this.language.Chinese;
      } else {
        this.languageCurent = this.language.English;
      }
    },

    // 获取建模场景信息
    getModelingSceneInfo(ModelingSceneID) {
      const _this = this;
      axios
        .post(config.httpIP + "getModelingSceneInfo", { id: ModelingSceneID })
        .then((resp) => {
          _this.containerID = resp.data.containerID;
          _this.code = resp.data.code;
          _this.projectName = resp.data.name;

          // 启动容器
          _this.startDockerContainer();
          // 获取python环境包信息
          _this.getPackageInfo();
          // 获取目录树信息
          _this.getDataTree();
        });
    },
    // 启动docker container
    startDockerContainer() {
      var postData = {
        containerID: this.containerID,
      };
      axios
        .post(config.httpIP + "startDockerContainer", postData)
        .then((resp) => {});
    },
    saveCode() {
      var postData = {
        id: this.sceneID,
        code: this.code,
      };

      axios.post(config.httpIP + "saveCode", postData).then((resp) => {
        if (resp.data == "success") {
          ElNotification.success({
            title: "Success",
            message: "Code saved successfully!",
            offset: 6,
          });
        } else {
          ElNotification.error({
            title: "Error",
            message: "Code save failed!",
            offset: 6,
          });
        }
      });
    },
    clean() {
      // 清除结果提示
      this.runingResult = "Response...\n";
    },
    /**地图相关方法 */
    // 地图初始化
    initMap() {
      /**图层 */
      /**谷歌地图图层 */
      // eslint-disable-next-line no-unused-vars
      const googleMapTerLayer = new TileLayer({
        source: new XYZ({
          attributions:
            'Tiles © <a href="https://services.arcgisonline.com/ArcGIS/' +
            'rest/services/World_Topo_Map/MapServer">ArcGIS</a>',
          url:
            "https://server.arcgisonline.com/ArcGIS/rest/services/" +
            "World_Topo_Map/MapServer/tile/{z}/{y}/{x}",
        }),
      }); //谷歌地图
      /**天地图图层 */
      const tdtMapVecLayer = new TileLayer({
        source: new XYZ({
          url: "http://t4.tianditu.com/DataServer?T=vec_w&tk=ba83a5dc9758ca23aea593a39d998825&x={x}&y={y}&l={z}",
        }),
      }); //天地图矢量图
      this.layers.push(tdtMapVecLayer);
      // eslint-disable-next-line no-unused-vars
      const tdtMapImgLayer = new TileLayer({
        source: new XYZ({
          url: "http://t4.tianditu.com/DataServer?T=img_w&tk=ba83a5dc9758ca23aea593a39d998825&x={x}&y={y}&l={z}",
        }),
      }); //天地图影像地图
      this.layers.push(tdtMapImgLayer);
      // var wangJiaba = new TileLayer({
      //   source: new TileWMSSource({
      //     url: "http://localhost:8050/geoserver/GHFSystemData/wms",
      //     params: {
      //       LAYERS: [
      //         "GHFSystemData:wangjiaba_BORDER",
      //         "GHFSystemData:wangjiaba_subBasin",
      //         "GHFSystemData:wangjiaba_stream",
      //       ],
      //     },
      //     serverType: "geoserver",
      //     crossOrigin: "anonymous",
      //   }),
      // });

      var tdtMapCva = new TileLayer({
        source: new XYZ({
          url: "http://t4.tianditu.com/DataServer?T=cva_w&tk=ba83a5dc9758ca23aea593a39d998825&x={x}&y={y}&l={z}",
        }),
      }); //天地图注记

      // eslint-disable-next-line no-unused-vars
      const OSMLayer = new TileLayer({
        source: new OSM(),
      }); //OSM地图
      const view = new View({
        center: [114.54346, 32.40582],
        zoom: 8,
        maxZoom: 18,
        projection: "EPSG:4326",
        constrainResolution: true, // 设置缩放级别为整数
        smoothResolutionConstraint: false, // 关闭无级缩放地图
      });
      var basinName = "wangjiaba";
      var saveBasinLayer = new TileLayer({
        source: new TileWMSSource({
          url: "http://localhost:8050/geoserver/GHFSystemData/wms",
          params: {
            LAYERS: [
              "GHFSystemData:huaibin_BORDER",

              "GHFSystemData:huaibin_SUBBASIN",
              "GHFSystemData:huaibin_river_network",
            ],
          },
          serverType: "geoserver",
          crossOrigin: "anonymous",
        }),
      });
      this.map = new Map({
        target: "mapContainer",
        logo: false,
        layers: [tdtMapVecLayer, tdtMapCva, saveBasinLayer],
        view: view,
        controls: defaultControls({
          zoom: false,
          attribution: false,
          rotate: false,
        }),
      });
      this.map.on("click", (e) => {});
    },
    // 判断map是否包含当前图层
    uniqueLayer(layer) {
      var mapTileLayers = this.map.getLayers().array_;
      for (let index = 0; index < mapTileLayers.length; index++) {
        const mapLayer = mapTileLayers[index];
        if (layer.ol_uid === mapLayer.ol_uid) {
          return true;
        }
      }
      return false;
    },
    insertLayers(layer, insertIndex) {
      // 插入图层，拓展图层数组
      this.map.addLayer(layer);

      var mapTileLayers = this.map.getLayers().array_;
      const layerCount = mapTileLayers.length;

      // 判断插入位置的合法性
      if (insertIndex < 3) {
        insertIndex = 3;
      } else if (insertIndex >= layerCount) {
        insertIndex = layerCount - 1;
      }

      // 调整图层位置
      for (let index = layerCount - 1; index > insertIndex; index--) {
        mapTileLayers[index] = mapTileLayers[index - 1];
      }
      mapTileLayers[insertIndex] = layer;
    },
    // 地图切换
    changeLayer(type) {
      switch (type) {
        case "tdtMap":
          //天地图矢量地图
          if (!this.uniqueLayer(this.layers[0])) {
            this.map.getLayers().removeAt(0);
            this.map.getLayers().insertAt(0, this.layers[0]);
          }
          break;
        case "tdtImg":
          //天地图影像地图
          if (!this.uniqueLayer(this.layers[1])) {
            this.map.getLayers().removeAt(0);
            this.map.getLayers().insertAt(0, this.layers[1]);
          }
          break;
        default:
          break;
      }
    },
    zoom(type) {
      const view = this.map.getView();
      const zoom = view.getZoom();
      switch (type) {
        case "zoomIn":
          view.setZoom(zoom + 1);
          break;
        case "zoomOut":
          view.setZoom(zoom - 1);
          break;
        default:
          break;
      }
    },

    /**代码相关方法 */
    // 代码重置
    codeReset() {
      this.code =
        "def print_hi(name):\n  print(f'Hello, {name}')\n\nif __name__ == '__main__':\n  print_hi('Hello world!')";
      this.socket.onClose = () => {
        console.log("WebSocket连接已关闭");
      };
    },

    runPython() {
      // 调用模型
      const postData = {
        containerID: this.containerID,
        projectID: this.projectID,
        projectName: this.projectName,
        code: this.code,
      };

      axios.post(config.httpIP + "runPython", postData).then((res) => {
        ElNotification.info({
          message: res.data,
          offset: 6,
        });
      });
    },
    creatWebSession() {
      // this.projectID = uuid.v4();
      this.projectID = this.sceneID;
      const _this = this;
      // 建立websocket连接
      const socket = new WebSocket(
        "ws://" + config.IP + "websocket/" + this.projectID
      );
      socket.onmessage = function (event) {
        // 接收到来自服务器的消息
        var message = event.data;
        if (message.includes("layer:")) {
          console.log(message);
          let layer = _this.projectName + ":" + message.split(":")[1];
          message += "  发布成功！";

          let tilLayer = new TileLayer({
            source: new TileWMSSource({
              url:
                "http://localhost:8050/geoserver/" + _this.projectName + "/wms",
              params: {
                LAYERS: [layer],
              },
              serverType: "geoserver",
              crossOrigin: "anonymous",
            }),
          });
          console.log(tilLayer);

          _this.insertLayers(tilLayer, 999);
        } else if (message.includes("文件已下载并保存为")) {
          _this.getDataTree();
        }
        // 将消息打印到输出控制台
        _this.runingResult += message;
      };

      this.socket = socket;
    },
    stopMoudle() {
      console.log("停止运行！");
      const _this = this;

      if (this.containerID == "") {
        ElNotification.error({
          message: "运行容器不存在",
          offset: 6,
        });
        return;
      }
      const postData = {
        containerID: this.containerID,
        projectID: this.projectID,
      };
      axios.post(config.httpIP + "stopPython", postData).then((res) => {
        ElNotification.info({
          message: res.data,
          offset: 6,
        });
        _this.socket.close();
      });
    },
    // 获取依赖包信息
    getPackageInfo() {
      const _this = this;
      const postData = {
        containerID: this.containerID,
        projectID: this.projectID,
        projectName: this.projectName,
      };
      axios.post(config.httpIP + "getLibraryInfo", postData).then((res) => {
        _this.packageInfor = res.data;
      });
    },
    // 添加移除依赖包
    editPackageInfo(type, index) {
      const _this = this;
      var postData = {
        containerID: this.containerID,
        type: type,
        name: "",
        version: "",
      };
      switch (type) {
        case "add":
          postData.name = this.addedPackageInfo.name;
          postData.version = this.addedPackageInfo.version;

          break;
        case "remove":
          postData.name = this.packageInfor[index].name;
          postData.version = this.packageInfor[index].version;
          break;
        default:
          break;
      }
      axios.post(config.httpIP + "packageOperation", postData).then((resp) => {
        // 获取python环境包信息
        _this.getPackageInfo();
        console.log(resp.data);
        var messagesArray = resp.data.content;

        var messagesStr = "";
        for (let index = 0; index < messagesArray.length; index++) {
          messagesStr += messagesArray[index];
        }

        console.log(messagesStr);
        if (resp.data.type == "error") {
          ElNotification.error({
            message: "Failed to update the dependency package",
            offset: 6,
          });
        } else {
          ElNotification.success({
            message: "The dependency package is updated successfully",
            offset: 6,
          });
        }
      });
    },
    // 组件展示控制器
    leftShowerController(index) {
      for (let i = 0; i < this.leftShower.length; i++) {
        if (i == index) {
          this.leftShower[i] = true;
        } else {
          this.leftShower[i] = false;
        }
      }
    },
    middleShowerController(index) {
      for (let i = 0; i < this.middleShower.length; i++) {
        if (i == index) {
          this.middleShower[i] = true;
        } else {
          this.middleShower[i] = false;
        }
      }
    },
    /**可视化方法 */
    geoViewer() {},
    /**获取数据 */
    getDataTree() {
      const _this = this;
      console.log(this.projectName);
      axios
        .post(config.httpIP + "getDataTree", { name: this.projectName })
        .then((resp) => {
          _this.dataTree = resp.data;
          console.log(_this.dataTree);
        });
    },
    // openFile
    async openFile(file, filetype) {
      let filesplt = file.split("\\");
      let filename = filesplt[filesplt.length - 1];
      let appendix = filename.split(".")[1];
      let previewItem;
      if (
        appendix == "png" ||
        appendix == "jpg" ||
        appendix == "jpeg" ||
        appendix == "gif" ||
        appendix == "svg" ||
        appendix == "bmp"
      ) {
        let ip = "http://172.21.212.124:6868";
        // const path = require("path");
        // console.log(file);
        // console.log(filesplt);
        let url = file.replace(/^E:\\DockerContainer/, ip);
        console.log("url:" + url);
        previewItem = {
          name: filename,
          url: url,
          srclist: [url],
          isImg: true,
        };
      } else {
        let ip = "http://172.21.212.124:6868";
        let content = "";
        // const path = require("path");
        // console.log(file);
        // console.log(filesplt);
        let url = file.replace(/^E:\\DockerContainer/, ip);
        console.log("url:" + url);
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        content = await response.text();
        previewItem = {
          name: filename,
          url: "filesImg/" + filetype + ".png",
          isImg: false,
          fileContent: content,
        };
      }
      let contains = false;
      this.dataPreviewList.forEach((item) => {
        if (item.name == previewItem.name) {
          contains = true;
        }
      });
      if (!contains) {
        this.dataPreviewList.push(previewItem);
      }

      console.log(file);
    },
    closePreview(index) {
      this.dataPreviewList.splice(index, 1);
    },
    openPreview(item) {
      this.dialogVisible = true;
      this.previewItem = item;
    },
  },

  mounted() {
    this.splitpaneVertical1Left = "30%";
    this.splitpaneVertical2Left = "70%";
    this.languageCurent = this.language.Chinese;
    this.initMap(); //地图初始化

    // 获取建模场景信息
    this.sceneID = this.$route.query.sceneID;
    // 建立socket连接
    this.creatWebSession();

    this.getModelingSceneInfo(this.sceneID);

    // this.dataPreviewList.push({
    //   name: "test11111111111111111111111111111111111111111111111111111111111",
    //   url: "http://172.21.213.60:8999/store/2016-04-17-36-0.png",
    //   srclist: ["http://172.21.213.60:8999/store/2016-04-17-36-0.png"],
    //   isImg: true,
    // });
  },
  beforeUnmount() {
    console.log("结束session");
    this.socket.close();
  },
  components: { Codemirror, ResourceList, Result, DataList, Graph },
};
</script>
<style lang="less" scoped>
.background {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  position: absolute;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.head {
  box-sizing: border-box;
  width: 100%;
  height: 65px;
  background: black;
}

.container {
  box-sizing: border-box;
  width: 100%;
  height: calc(100% - 71px);
  display: flex;
  flex-direction: column;
  margin-top: 6px;
  position: relative;
  border-radius: 3px;
  background: #fff;
  border-color: #f3f3f3;
  border-width: 2px;
  border-style: solid;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
}
.container .code-container {
  width: 100%;
  height: 50%;
  // background: black;
  box-sizing: border-box;
  display: flex;
  position: relative;
}
.container .visual-container {
  width: 100%;
  height: 50%;
  // background: black;
  box-sizing: border-box;
  position: relative;
  padding-top: 8px;
}
.container .left-container {
  width: 30%;
  height: 100%;
  // background: red;
  padding-top: 46px;
  padding-bottom: 5px;
  // padding-right: 10px;
  box-sizing: border-box;
  position: relative;
}
.container .middle-container {
  width: 50%;
  height: 100%;
  // background: green;
  box-sizing: border-box;
  padding-left: 8px;
  padding-top: 40px;
  position: relative;
  display: flex;
  flex-direction: column;
}
.container .right-container {
  width: 20%;
  height: 100%;
  // background: blue;
  box-sizing: border-box;
  padding-left: 8px;
  padding-top: 40px;
  position: relative;
}
.container .splitpane-handle-vertical {
  background-color: #f5f5f5;
  background-repeat: no-repeat;
  background-position: center;

  background-image: url(../assets/img/vertical_handle.png),
    -webkit-linear-gradient(left, #f5f5f5, #f1f1f1);
  cursor: col-resize;
  border-left-width: 1px;
  border-right-width: 1px;
  width: 8px;
  position: absolute;
  overflow: hidden;
  z-index: 2;
  left: 1010.81px;
  top: 0px;
  box-sizing: border-box;
  height: 100%;
}

.container .splitpane-handle-horizontal {
  background-color: #f5f5f5;
  background-repeat: no-repeat;
  background-position: center;
  border-color: #dcdcdc;
  border-style: solid;
  border-width: 0;

  background-image: url("../assets/img/handle.png"),
    -webkit-linear-gradient(top, #f5f5f5, #f1f1f1);
  background-position-y: 0;
  cursor: row-resize;
  border-top-width: 1px;
  border-bottom-width: 1px;
  width: 100%;
  height: 8px;
  position: absolute;
  overflow: hidden;
  z-index: 10;
  left: 0px;
  top: 50%;
  box-sizing: border-box;
}
.container-topbar {
  position: absolute;
  z-index: 9;
  box-sizing: border-box;
  top: 5px;
  left: 10px;
  width: fit-content;
  height: 32px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  background-color: #f4f4f4;
  border-radius: 5px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 5px;

  // background-color: red;
}
.container-topbar .topbar-item {
  float: right;
  height: fit-content;
  padding: 0 12px;
  border-right: 2px #dbdee2 dashed;
  vertical-align: middle;
  cursor: pointer;
  overflow: visible;
  zoom: 1;
  color: #5f6477;
  font-size: 15px;
}
.container-topbar .topbar-item:hover {
  color: #1479d7;
}

.visual-container .map-container {
  width: 100%;
  height: 100%;
}
.visual-container .map-container .map-card {
  position: absolute;
  z-index: 9;
  display: flex;
  flex-direction: column;
  left: 10px;
  bottom: 6px;
  font-size: 18px;
  cursor: pointer;
  justify-content: space-between;
  height: 66px;
  width: 20px;
  padding: 5px 3px;
  background-color: #fff;
  color: rgb(110, 105, 102);
  border-radius: 5px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
}
.visual-container .map-container .map-card .icon:hover {
  color: rgb(20, 121, 215);
}

.visual-container .map-container .layers {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  position: absolute;
  left: 40px;
  bottom: 42px;
  z-index: 9;
  background: #fff;
  padding: 5px 5px;
  border-radius: 5px;
  box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3),
    0 1px 3px 1px rgba(60, 64, 67, 0.15);
}
.visual-container .map-container .layers .layer-box {
  margin: 0 2px;
  position: relative;
  height: fit-content;
  width: fit-content;
  border: 1px solid rgb(204, 201, 201);

  border-radius: 2px;
}
.visual-container .map-container .layers .layer-box:hover {
  border-color: rgb(20, 121, 215);
}

.visual-container .map-container .layers .layer-box:hover p {
  background: rgb(20, 121, 215);
}

.visual-container .map-container .layers .layer-box img {
  width: 60px;
  height: 50px;
  object-fit: cover;
}

.visual-container .map-container .layers .layer-box p {
  position: absolute;
  bottom: 0;
  left: 0;
  font-size: 12px;
  margin: 0px;
  color: #fff;
  padding: 2px 4px;
  background: rgba(128, 128, 128, 0.664);
}
.visual-container .chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  padding-top: 55px;
  padding-left: 15px;
  padding-right: 15px;
  box-sizing: border-box;
}
.visual-container .chart-container .card {
  position: relative;
  width: 150px;
  display: flex;
  flex-direction: column;
  justify-items: center;
  justify-content: center;
  align-content: center;
  align-items: center;
  height: 220px;
  border: 1px solid #d8cfcf;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
  transition: 0.3s; /* 添加过渡效果 */
  // width: 300px; /* 设置卡片宽度 */
  padding: 22px 10px; /* 设置内边距 */
  padding-bottom: 0px;
  border-radius: 5px; /* 设置圆角 */
  background-color: #ffffff; /* 设置背景色 */
  margin-right: 25px;
}
.visual-container .chart-container .card .close_icon {
  position: absolute;
  right: 8px;
  top: 5px;
  color: #5f6477;
  &:hover {
    cursor: pointer;
  }
}

.visual-container .chart-container .card .chart-prew {
  width: 100%;
  height: 90%;
  display: flex;
  justify-content: center;
  align-items: center;

  padding: 0px;
}
.visual-container .chart-container .card .preview_text {
  width: 100%;
  height: 100%;
  margin: 0;
  overflow: hidden;

  &:hover {
    cursor: pointer;
  }
}
.visual-container .chart-container .card .title-container {
  width: 100%;
  height: 10%;
  display: flex;

  justify-content: center;
  align-items: center;
  // background-color: rgb(138, 85, 85);
  font-size: 12px;
  overflow: hidden;
}
.library-container {
  position: absolute;
  top: 100px;
  left: 50%;
  z-index: 10;
  width: fit-content;
  height: fit-content;
  transform: translateX(-50%);
  box-shadow: 0 2px 2px #888888;
  background: white;
  border: 1px solid #9a9a9a;
  border-radius: 6px;
}
.library-container .addPackage {
  width: 100%;
  height: 38px;
  display: flex;
  align-items: center;
  // background: red;
}
.library-container .package-info {
  display: flex;
  align-items: center;
  margin-right: 5px;
}
.library-container .package-info label {
  color: #606266;
  margin-right: 2px;
  font-size: 14px;
}
.library-container .package-info /deep/ .el-input__inner {
  font-size: 13px;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
::v-deep .el-dialog__body {
  padding: 0;
  padding-bottom: 20px;
}
.clean {
  position: absolute;
  right: 8px;
  bottom: 8px;
}
</style>